import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter_app/common/global.dart';
import 'package:flutter_app/model/news.dart';
import 'package:flutter_app/model/tweet.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import 'utils.dart';
import 'package:image/image.dart' as imageProcessing;
import '../model/image.dart' as modelImage;

class m_http {
  static Future<String> issueTweet(Tweet tweet) async {
    if (Global.userId.length == 0) {
      Global.userId = await getUserId();
      final prefs = await SharedPreferences.getInstance();
      prefs.setString("userId", Global.userId);
    }
    if (Global.userId.length == 0) {
      return "当前状态无法发布动态。";
    }

    String paramStr =
        // '{"issuer":{"id":"${Global.userId}"},"text":"${tweet.text}","images":"${tweet.images.join("|")}","thumbnails":"${tweet.thumbnails.join("|")}"}';
        '{"issuer":{"id":"${Global.userId}"},"text":"${tweet.text}","images":"${m_utils.encodeStringArraytoJson(tweet.images)}","thumbnails":"${m_utils.encodeStringArraytoJson(tweet.thumbnails)}"}';
    http.Response response =
        await http.post(Global.serversUrl + "/Tweet", body: paramStr);
    //解析响应字符串，并生成Json对象
    return json.decode(response.body);
  }

  static Future<String> issueReply(Reply reply) async {
    if (Global.userId.length == 0) {
      Global.userId = await getUserId();
      final prefs = await SharedPreferences.getInstance();
      prefs.setString("userId", Global.userId);
    }
    if (Global.userId.length == 0) {
      return "当前状态无法发布回复。";
    }

    String paramStr =
        // '{"issuer":{"id":"${Global.userId}"},"text":"${tweet.text}","images":"${tweet.images.join("|")}","thumbnails":"${tweet.thumbnails.join("|")}"}';
        '{"issuer":{"id":"${Global.userId}"},"text":"${reply.text}","tweet":{"id":"${reply.tweetId}"}}';
    http.Response response =
        await http.post(Global.serversUrl + "/Reply", body: paramStr);
    //解析响应字符串，并生成Json对象
    return json.decode(response.body);
  }

  static Future<String> getUserId() async => http
          .get(Global.serversUrl + "/generateUserId")
          .timeout(Duration(milliseconds: 2500))
          .then((response) {
        if (response?.statusCode == 200) {
          return response.body;
        } else {
          return "";
        }
      }).catchError((error) {
        return "";
      });

  static Future<List<Tweet>> getTweetList(Map<String, dynamic> map) async {
    List<Tweet> tweetList = [];
    http.Response response = await http.get(Global.serversUrl +
        "/TweetList?p=${map["p"]}&refreshTime=${map["refreshTime"]}&userId=${map["userId"]}");
    // var dio = new Dio();
    // Response<dynamic> response =
    //     await dio.get(Global.serversUrl + "/TweetList", queryParameters: map);
    List<dynamic> reultTweetList = json.decode(response.body);
    if (reultTweetList.length > 0) {
      for (dynamic reultTweet in reultTweetList) {
        tweetList.add(Tweet.fromJson(reultTweet));
      }
    }

    return tweetList;
  }

  static Future<List<News>> getNewsList(Map<String, dynamic> map) async {
    List<News> newsList = [];
    http.Response response = await http.get(Global.serversUrl +
        "/NewsList?p=${map["p"]}&refreshTime=${map["refreshTime"]}");
    // var dio = new Dio();
    // Response<dynamic> response =
    //     await dio.get(Global.serversUrl + "/TweetList", queryParameters: map);
    List<dynamic> reultNewsList = json.decode(response.body);
    if (reultNewsList.length > 0) {
      for (dynamic reultNews in reultNewsList) {
        newsList.add(News.fromJson(reultNews));
      }
    }

    return newsList;
  }

  //执行上传操作
  static Future<Map> doUpload(
      imageType, List<int> imageBytes, List<int> thumbnailBytes) async {
    Map<String, dynamic> result = new Map();
    try {
      //请求获取上传权限和地址等参数。
      Map<String, dynamic> token = await getUploadToken(imageType);
      token["imageBytes"] = imageBytes;
      token["thumbnailBytes"] = thumbnailBytes;

      //上传图片
      bool res = await putImg(token);

      if (res) {
        //上传缩略图
        res = await putThumbnail(token);
        if (res) {
          result["msg"] = "ok";
          result["imageName"] = token['imageName'];
          result["thumbnailName"] = token['thumbnailName'];
          return result;
        }
      }
      result["msg"] = "fail";
      return result;
    } catch (e) {
      print(e.toString());
      result["msg"] = "fail";
      return result;
    }
  }

  //获取上传的token
  static Future<Map<String, dynamic>> getUploadToken(String imageType) async {
    http.Response response = await http
        // .get("http://192.168.31.52:8080/getUploadAuthority/" + fileType);
        .get(Global.serversUrl + "/getUploadAuthority/" + imageType);
    //解析响应字符串，并生成Json对象
    Map repos = json.decode(response.body);
    return repos;
  }

  //上传图片
  static Future<bool> putImg(dynamic token) {
    return httpPutImg(token['imageUrl'], token['date'],
        token['imageAuthorization'], token['imageBytes']);
  }

//上传缩略图
  static Future<bool> putThumbnail(dynamic token) {
    return httpPutImg(token['thumbnailUrl'], token['date'],
        token['thumbnailAuthorization'], token['thumbnailBytes']);
  }

//发送图片到obs对象存储
  static Future<bool> httpPutImg(
      String url, String date, String authorization, List<int> bytes) async {
    http.Response response = await http.put(url,
        headers: {
          HttpHeaders.dateHeader: date,
          HttpHeaders.authorizationHeader: authorization
        },
        body: bytes);
    if (response.statusCode == 200) {
      return true;
    } else {
      print(response.statusCode);
      return false;
    }
  }

  //上传图片文件（上传图片操作的入口）
  static Future<Map> uploadImageFile(modelImage.Image image) async {
    String filetype = m_utils.getFileType(image.filePath);
    //获取文件字节数组
    // Stream<List<int>> stream = imageFile.openRead();
    // List<int> bytes = await new http.ByteStream(stream).toBytes();
    List<int> bytes = await new File(image.filePath).readAsBytes(); //这种方式速度较慢

    //生成缩略图
    imageProcessing.Image thumbnail = modelImage.Image.generateThumbnail(
        imageProcessing.decodeImage(bytes), image.compressionType);

    //上传
    Map<String, dynamic> resultMsg = await doUpload(filetype, bytes,
        imageProcessing.encodeNamedImage(thumbnail, "." + filetype));
    return resultMsg;
    //return {};
  }

  //是否已点赞tweet
  static Future<List<Tweet>> tweetIsLiked(Map map) async {
    var dio = new Dio();

    List<Tweet> tweetList = map["tweetList"];
    List<String> tweetIdList = [];
    for (Tweet tweet in tweetList) {
      tweetIdList.add(tweet.id);
    }

    Response<dynamic> response = await dio.post(
        Global.serversUrl + "/TweetIsLiked",
        queryParameters: {"tweetIdList": tweetIdList, "userId": map["userId"]});
    List result = jsonDecode(response.toString());
    for (var i = 0; i < tweetList.length; i++) {
      print(tweetList[i].id + "|" + result[i]["tweetId"]);
      tweetList[i].isFavorited = result[i]["isLiked"];
    }

    return tweetList;
  }
}
